/*
 * Copyright (c) 2016, Freescale Semiconductor, Inc.
 * Copyright 2016-2020 NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

/*******************************************************************************
 * Includes
 ******************************************************************************/

#include "fsl_debug_console.h"
#include "pin_mux.h"
#include "board.h"
#include "fsl_ctimer.h"

#include <stdbool.h>
/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define CTIMER          CTIMER0         /* Timer 0 */
#define CTIMER_MAT_OUT  kCTIMER_Match_0 /* Match output 0 */
#define CTIMER_CLK_FREQ CLOCK_GetFreq(kCLOCK_CoreSysClk)

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Variables
 ******************************************************************************/

/*******************************************************************************
 * Code
 ******************************************************************************/

/*!
 * @brief Main function
 */
int main(void)
{
    ctimer_config_t config;
    ctimer_match_config_t matchConfig;
		volatile uint32_t timer = 0;
	
    /* Init hardware*/
    /* Attach 12 MHz clock to USART0 (debug console) */
    CLOCK_Select(BOARD_DEBUG_USART_CLK_ATTACH);

    BOARD_InitBootPins();
    BOARD_InitBootClocks();
    BOARD_InitDebugConsole();

#if defined(BOARD_HAS_NO_CTIMER_OUTPUT_PIN_CONNECTED_TO_LED)
    LED_RED1_INIT(LOGIC_LED_OFF);
#endif

    PRINTF("CTimer match example to toggle the output on a match\r\n");

    CTIMER_GetDefaultConfig(&config);

    CTIMER_Init(CTIMER, &config);

    matchConfig.enableCounterReset = false;
    matchConfig.enableCounterStop  = false;
    matchConfig.matchValue         = CTIMER_CLK_FREQ;
    matchConfig.outControl         = kCTIMER_Output_NoAction;
    matchConfig.outPinInitState    = false;
    matchConfig.enableInterrupt    = false;
    CTIMER_SetupMatch(CTIMER, CTIMER_MAT_OUT, &matchConfig);
    CTIMER_StartTimer(CTIMER);


		CTIMER_Reset(CTIMER);
		for(uint32_t i=0;i<100;i++)
			__NOP();
		timer =	CTIMER_GetTimerCountValue(CTIMER);
		PRINTF("%d\r\n",timer);
		
		CTIMER_Reset(CTIMER);
		for(uint32_t i=0;i<200;i++)
			__NOP();
		timer =	CTIMER_GetTimerCountValue(CTIMER);
		PRINTF("%d\r\n",timer);

		CTIMER_Reset(CTIMER);
		for(uint32_t i=0;i<1000;i++)
			__NOP();
		timer =	CTIMER_GetTimerCountValue(CTIMER);
		PRINTF("%d\r\n",timer);

    while (1)
    {
				__WFI();
    }
}
